package com.inf.utils;

import com.sun.jersey.core.util.Base64;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by zhangbn on 2018/11/14.
 */
@Component
public class Tools implements ApplicationContextAware {

    static Logger log = LoggerFactory.getLogger(Tools.class);

    private static ApplicationContext applicationContext;

    private static List<byte[]> listN = new ArrayList<>();

    /**
     * 从相似度数组中找出最大的及其在数组中的位置
     *
     * @param dArr
     * @return
     */
    public static Map<Integer, Double> getMaxScoreAndIdx(double[] dArr) {
        Map<Integer, Double> map = new HashMap<Integer, Double>();
        Double maxSocre = Double.MIN_VALUE;
        Integer index = Integer.MIN_VALUE;
        for (int i = 0; i < dArr.length; i++) {
            if (dArr[i] - maxSocre > 0) {
                maxSocre = dArr[i];
                index = i;
            }
        }
        map.put(index, maxSocre);
        return map;
    }

    /**
     * 格式化传入的时间参数
     *
     * @param oriStr
     * @param destPattern
     * @return
     * @throws Exception
     */
    public static String formatTimeStr(String oriStr, String destPattern) throws Exception {
        DateTimeFormatter format = null;
        if (oriStr.trim().length() == 10) {
            format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        } else if (oriStr.trim().length() == 19) {
            format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        } else {
            throw new Exception("传入的时间[" + oriStr + "]格式不正确!");
        }
        DateTimeFormatter format_use = DateTimeFormatter.ofPattern(destPattern);
        LocalDateTime oriTime = LocalDateTime.parse(oriStr, format);
        String destTimeStr = oriTime.format(format_use);
        return destTimeStr;
    }

    /**
     * 处理相机组字符串
     *
     * @param cameraIds
     * @return
     */
    public static String cameraIdsMakeStrForSql(String cameraIds) {
        String destStr = "";
        if (cameraIds == null || cameraIds.toLowerCase().equals("null")) {
            return destStr;
        }
        cameraIds = cameraIds.trim();
        if (StringUtils.isNotBlank(cameraIds)) {
            List<String> idList = Arrays.asList(cameraIds.split(","));
            StringBuffer sb = new StringBuffer(" (");
            for (String id : idList) {
                sb.append("'").append(id).append("'").append(",");
            }
            destStr = sb.substring(0, sb.length() - 1) + ") ";
        }
        return destStr;
    }


    /**
     * 获取缓存的特征码
     *
     * @return
     */
    public static List<byte[]> getPersonRepoFeatureList() {
        if (listN.isEmpty()) {
            synchronized (listN) {
                if (listN.isEmpty()) {
                    log.info("\n\n");
                    log.info("show: 开始缓存人员库中的特征码......");
                    log.info("\n\n");
                    JedisPool jedisPool = (JedisPool) applicationContext.getBean(JedisPool.class);
                    Jedis jedis = jedisPool.getResource();
                    listN = jedis.lrange("featureList", 0, -1).stream().map(e -> Base64.decode(e)).collect(Collectors.toList());
                    log.info("\n\n");
                    log.info("show: 缓存人员库中的特征码完成，ListN.size()=" + listN.size());
                    log.info("\n\n");
                }
            }
        }
        log.info("\n\n");
        log.info("show: 获取缓存中的特征码.....................................................");
        log.info("\n\n");
        return listN;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (Tools.applicationContext == null) {
            Tools.applicationContext = applicationContext;
        }
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}
